package org.spring.qq_chat_java.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.profile.DefaultProfile;
import org.spring.qq_chat_java.constant.oss;

import java.net.URL;
import java.util.Date;

public class OssUtils {

    public static String buildAliyunSTSCredentials(String fileName) throws ClientException, com.aliyuncs.exceptions.ClientException {
        // 创建默认的 profile，并指定 region ID
        IClientProfile profile = DefaultProfile.getProfile(
                "cn-shenzhen",
                oss.OSSAccessKeyId,
                oss.accessSecret
        );

        // 如果需要自定义 endpoint，可以使用以下方式添加（推荐通过配置或DNS实现）
        // 或者使用 DefaultProfile.getProfile(...) 时自动从服务发现获取

        DefaultAcsClient client = new DefaultAcsClient(profile);

        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setSysMethod(MethodType.POST);            // 替代 setMethod()
        request.setSysProtocol(ProtocolType.HTTPS);      // 替代 setProtocol()
        request.setDurationSeconds(900L);
        request.setRoleArn("acs:ram::1506525426020212:role/shaun");
        request.setRoleSessionName("shaun");

        // 生成临时授权凭证
        final AssumeRoleResponse response = client.getAcsResponse(request);

        if (response == null) {
            return null;
        }

        // 获取 STS 凭证
        String accessKeyId = response.getCredentials().getAccessKeyId();
        String accessKeySecret = response.getCredentials().getAccessKeySecret();
        String securityToken = response.getCredentials().getSecurityToken();

        // 使用 STS 凭证创建 OSSClient
         OSS ossClient = new OSSClientBuilder().build(
                 oss.endpoint,
                 accessKeyId,
                 accessKeySecret,
                 securityToken);


        // 设置签名URL过期时间为300秒（5分钟）
        Date expiration = new Date(System.currentTimeMillis() + 300 * 1000);
        URL url = ossClient.generatePresignedUrl(oss.bucket, fileName, expiration);

        ossClient.shutdown();

        return url.toString();
    }
}
